class MagifierTools {
  static initializeCanvas(
    canvas: HTMLCanvasElement,
    magnifier: HTMLCanvasElement,
    imgSrc: string,
    magnifierSize: number,
    zoom:number
  ) {
    const ctx = canvas.getContext('2d');
    const magnifierCtx = magnifier.getContext('2d');
    const img = new Image();
    img.src = imgSrc;

    img.onload = () => {
      function resizeCanvas() {
        if (canvas && ctx && img) {
          const rect = canvas.getBoundingClientRect();
          canvas.width = rect.width;
          canvas.height = rect.width * (img.height / img.width);

          ctx.clearRect(0, 0, canvas.width, canvas.height);
          ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
        }
      }

      resizeCanvas();
      window.addEventListener('resize', resizeCanvas);

      canvas.addEventListener('mousemove', (e) => {
        if (magnifier && magnifierCtx) {
          const rect = canvas.getBoundingClientRect();
          const x = e.clientX - rect.left;
          const y = e.clientY - rect.top;

          magnifier.style.display = 'block';
          magnifier.style.left = `${x}px`;
          magnifier.style.top = `${y}px`;

          const magnifierRadius = magnifierSize;
          const Z = zoom;

          magnifier.width = magnifierRadius * 2;
          magnifier.height = magnifierRadius * 2;

          magnifierCtx.clearRect(0, 0, magnifier.width, magnifier.height);

          const scaleX = img.width / canvas.width;
          const scaleY = img.height / canvas.height;

          magnifierCtx.drawImage(
            img,
            (x * scaleX) - (magnifierRadius / Z),
            (y * scaleY) - (magnifierRadius / Z),
            magnifierRadius * 2 / Z,
            magnifierRadius * 2 / Z,
            0,
            0,
            magnifier.width,
            magnifier.height
          );
        }
      });

      canvas.addEventListener('mouseleave', () => {
        if (magnifier) {
          magnifier.style.display = 'none';
        }
      });
    };
  }
}

export default MagifierTools;
